//
//  LGTeamMemberController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/2/16.
//  团队成员列表：添加、删除、设置管理员

#import "LGTeamMemberController.h"
//用户详情
#import "LGPersionalDataController.h"

#import "LGTeamMemberCell.h"

#import "LGTeamMemberModel.h"

@interface LGTeamMemberController ()<UITableViewDelegate,UITableViewDataSource,LGTeamMemberDelegate>
/**   */
@property (nonatomic , strong)UIButton *deleteBtn;
/**   */
@property (nonatomic , strong)UIButton *searchBtn;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *sureBtn;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSMutableArray *selectArray;
/**   */
@property (nonatomic , copy)NSString *action;

@end

@implementation LGTeamMemberController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.teamId = (_teamId.length>0)?_teamId:@"0";
    [self.view addSubview:self.searchBtn];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.sureBtn];
    [self emptyViewWithSuperView:self.view frame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight)];
    [self requestData];
    
}

-(void)setType:(NSString *)type{
    _type = type;
    if([type isEqualToString:@"add"]){
        //添加成员
        self.title = @"添加团队成员";
        self.action = @"/doctor/select/doctorSelect";
        self.sureBtn.hidden = NO;
        self.tableView.frame = CGRectMake(0, kMaxY(self.searchBtn.frame)+viewPix(5), Screen_W, Screen_H-topBarHeight-kMaxY(self.searchBtn.frame)-viewPix(5)-viewPix(60)-bottomSafeBarHeight/2.0);
        
    }else if ([type isEqualToString:@"delete"]){
        //删除成员
        self.title = @"删除团队成员";
        self.action = @"/doctor/select/doctorSelectToDel";
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.deleteBtn];
        self.sureBtn.hidden = YES;
        self.tableView.frame = CGRectMake(0, kMaxY(self.searchBtn.frame)+viewPix(5), Screen_W, Screen_H-topBarHeight-kMaxY(self.searchBtn.frame));
        
    }else if ([type isEqualToString:@"manage"]){
        //设置管理员
        self.title = @"管理员设置";
        self.action = @"/doctor/select/doctorSelectToDel";
        self.sureBtn.hidden = YES;
        self.tableView.frame = CGRectMake(0, kMaxY(self.searchBtn.frame)+viewPix(5), Screen_W, Screen_H-topBarHeight-kMaxY(self.searchBtn.frame));
    }
}

-(void)requestData{
    [RequestUtil withPOST:self.action parameters:@{@"keyword":@"",@"teamid":self.teamId} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(code == 200){
            self.dataArray = [LGTeamMemberModel mj_objectArrayWithKeyValuesArray:returnData];
        }
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:LGEmptyPicName content:@"暂无团队成员" offset:0];
        }
        [self.tableView reloadData];
    } error:^(NSError *error) {
        self.isfirst = NO;
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:LGEmptyPicName content:LGErrorMessage offset:0];
        }
    }];
}

-(void)searchBtnAction{
    
}

-(void)sureBtnAction{
    NSMutableArray *tempArray = [NSMutableArray array];
    for (LGTeamMemberModel *model in self.dataArray) {
        if(model.isinto == YES){
            [tempArray addObject:@{@"userid":model.userid,@"ismanage":@"false"}];
        }
    }
    for (NSInteger i=0; i<self.selectArray.count; i++) {
        [tempArray addObject:@{@"userid":self.selectArray[i],@"ismanage":@"false"}];
    }
    [RequestUtil withPOST:@"/doctor/my.teams/save" parameters:@{@"teamid":self.teamId,@"title":self.teamTitle,@"desc":self.teamIntroduce,@"members":tempArray} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            if(self.backVC){
                [self.navigationController popToViewController:self.backVC animated:YES];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:LGErrorMessage offset:0];
    }];
}

//删除团队成员
-(void)deleteBtnAction{
    if(self.selectArray.count == 0){
        [TooltipView showMessage:@"请选择要删除的成员" offset:0];
        return;
    }
    NSString *userids = @"";
    for (NSInteger i=0; i<self.selectArray.count; i++) {
        userids = (userids.length>0)?[NSString stringWithFormat:@"%@,%@",userids,self.selectArray[i]]:self.selectArray[i];
    }
    [RequestUtil withPOST:@"/doctor/my.teams/delTeamMembers" parameters:@{@"teamid":self.teamId,@"userids":userids} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            if(self.backVC){
                [self.navigationController popToViewController:self.backVC animated:YES];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:LGErrorMessage offset:0];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGTeamMemberCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.type = self.type;
    cell.delegate = self;
    
    LGTeamMemberModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    cell.isSelect = [self.selectArray containsObject:model.userid]?YES:NO;
    cell.lineView.hidden = (indexPath.row == self.dataArray.count-1)?YES:NO;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //跳转用户详情
    LGTeamMemberModel *model = self.dataArray[indexPath.row];
    LGPersionalDataController *controller = [[LGPersionalDataController alloc]init];
    controller.userId = model.userid;
    [self.navigationController pushViewController:controller animated:YES];
}

//选择成员
-(void)selectTeamMember:(NSString *)userid select:(BOOL)select{
    if(select == YES){
        [self.selectArray addObject:userid];
    }else{
        [self.selectArray removeObject:userid];
    }
    if([self.type isEqualToString:@"add"]){
        //添加成员
        NSString *count = (self.selectArray.count == 0)?@"完成":[NSString stringWithFormat:@"完成（%ld）",self.selectArray.count];
        [self.sureBtn setTitle:count forState:UIControlStateNormal];
        self.sureBtn.selected = (self.selectArray.count > 0)?NO:YES;
        self.sureBtn.userInteractionEnabled = (self.selectArray.count > 0)?YES:NO;
        
    }else if ([self.type isEqualToString:@"delete"]){
        //删除成员
        NSString *count = (self.selectArray.count == 0)?@"删除":[NSString stringWithFormat:@"删除（%ld）",self.selectArray.count];
        [self.deleteBtn setTitle:count forState:UIControlStateNormal];
        self.deleteBtn.selected = (self.selectArray.count > 0)?YES:NO;
        
    }else if ([self.type isEqualToString:@"manage"]){
        //设置管理员
        [RequestUtil withPOST:@"/doctor/my.teams/saveTeamManage" parameters:@{@"teamid":self.teamId,@"userid":userid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [TooltipView showMessage:@"设置成功" offset:0];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:LGErrorMessage offset:0];
        }];
    }
}


#pragma mark
#pragma mark ====> 创建控件

-(NSMutableArray *)selectArray{
    if(!_selectArray){
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

-(UIButton *)deleteBtn{
    if(!_deleteBtn){
        _deleteBtn = [UIButton buttonWithTitle:@"删除" titleFont:LGFontWeight(15, UIFontWeightMedium) textColor:@"#EB5757" imageName:@""];
        _deleteBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _deleteBtn.frame = CGRectMake(0, 0, 85, 44);
        [_deleteBtn addTarget:self action:@selector(deleteBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}

-(UIButton *)searchBtn{
    if(!_searchBtn){
        _searchBtn = [UIButton buttonWithTitle:@"搜索" titleFont:LGFont(16) textColor:@"#999999" imageName:@"searchGray"];
        [_searchBtn addTarget:self action:@selector(searchBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchBtn;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kMaxY(self.searchBtn.frame)+viewPix(5), Screen_W, Screen_H-topBarHeight-kMaxY(self.searchBtn.frame)-viewPix(5)-viewPix(60)-bottomSafeBarHeight/2.0) style:UITableViewStylePlain];
        [_tableView registerClass:[LGTeamMemberCell class] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = viewPix(60);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(25))];
        _tableView.tableFooterView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(25))];
    }
    return _tableView;
}

-(UIButton *)sureBtn{
    if(!_sureBtn){
        _sureBtn = [UIButton buttonWithTitle:@"完成" topMargin:Screen_H-topBarHeight-viewPix(60)-bottomSafeBarHeight/2.0];
        _sureBtn.selected = YES;
        _sureBtn.userInteractionEnabled = NO;
        [_sureBtn addTarget:self action:@selector(sureBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
